import { Sequelize } from 'sequelize';
import config from '../config/database';

// 导入模型
import Article from './Article';
import Category from './Category';
import Tag from './Tag';
import Comment from './Comment';
import User from './User';
import Role from './Role';
import Permission from './Permission';

// 创建数据库连接
const env = process.env.NODE_ENV || 'development';
const dbConfig = config[env];

let sequelize: Sequelize;

if (dbConfig.url) {
  sequelize = new Sequelize(dbConfig.url, dbConfig);
} else {
  sequelize = new Sequelize(
    dbConfig.database,
    dbConfig.username,
    dbConfig.password,
    dbConfig
  );
}

// 初始化模型
Article.initialize(sequelize);
Category.initialize(sequelize);
Tag.initialize(sequelize);
Comment.initialize(sequelize);
User.initialize(sequelize);
Role.initialize(sequelize);
Permission.initialize(sequelize);

// 建立模型之间的关联关系
Article.associate({
  Category,
  Tag,
  Comment,
  User,
});

Category.associate({
  Article,
  Category, // 自关联，处理父子分类
});

Tag.associate({
  Article,
});

Comment.associate({
  Article,
  User,
  Comment, // 自关联，处理评论回复
});

User.associate({
  Article,
  Comment,
  Role,
});

Role.associate({
  User,
  Permission,
});

Permission.associate({
  Role,
});

// 导出模型和Sequelize实例
export {
  sequelize,
  Sequelize,
  Article,
  Category,
  Tag,
  Comment,
  User,
  Role,
  Permission,
};

// 默认导出所有模型
export default {
  sequelize,
  Sequelize,
  Article,
  Category,
  Tag,
  Comment,
  User,
  Role,
  Permission,
};
